<template>
    <div class="preview-dialog">
        <!-- 图片预览 -->
        <el-image-viewer v-if="visible && type === 'images'" :url-list="[url]" :initial-index="0"
            @close="handleClose" />

        <!-- 视频预览 -->
        <el-dialog v-model="dialogVisible" :title="title" width="800px" destroy-on-close v-if="type === 'videos'">
            <div class="video-player">
                <video controls :src="url" class="video-content" preload="metadata" controlsList="nodownload">
                    您的浏览器不支持 video 标签。
                </video>
            </div>
        </el-dialog>

        <!-- 音频预览 -->
        <el-dialog v-model="dialogVisible" :title="title" width="500px" destroy-on-close v-if="type === 'audios'">
            <div class="audio-player">
                <audio controls :src="url" class="audio-content">
                    您的浏览器不支持 audio 标签。
                </audio>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElImageViewer } from 'element-plus'

const props = defineProps<{
    visible: boolean
    url: string
    type: string
    title?: string
}>()

const emit = defineEmits<{
    (e: 'update:visible', value: boolean): void
}>()

const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
})

const handleClose = () => {
    emit('update:visible', false)
}

// 监听visible变化，同步dialogVisible
watch(() => props.visible, (newVal) => {
    if (newVal) {
        // 如果不是可预览的类型，直接下载
        if (!['images', 'videos', 'audios'].includes(props.type)) {
            window.open(props.url)
            emit('update:visible', false)
            return
        }
        dialogVisible.value = newVal
    } else {
        dialogVisible.value = newVal
    }
})
</script>

<style scoped lang="scss">
.video-player {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 70vh;
    background-color: #000;

    .video-content {
        width: 100%;
        height: 100%;
        object-fit: contain;
    }
}

.audio-player {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;

    .audio-content {
        width: 100%;
    }
}

:deep(.el-dialog__body) {
    padding: 0;
}
</style>